
let Vue
class Store {
  constructor(options = {}) {
    // 添加响应式的能力，直接利用vue的响应能力
    this.vm = new Vue({
      data: {
        state: options.state
      }
    })

    // getters
    let getters = options.getters || {}
    this.getters = {}
    Object.keys(getters).forEach(getterName => {
      Object.defineProperty(this.getters, getterName, {
        get: () => {
          return getters[getterName](this.state)
        }
      })
    })

    // mutations
    let mutations = options.mutations || {}
    this.mutations = {}
    Object.keys(mutations).forEach(mutationName => {
      this.mutations[mutationName] = (arg) => {
        mutations[mutationName](this.state, arg)
      }
    })

    // actions
    let actions = options.actions || {}
    this.actions = {}
    Object.keys(actions).forEach(actionName => {
      this.actions[actionName] = (arg) => {
        actions[actionName](this, arg)
      }
    })

  }

  get state() {
    return this.vm.state
  }

  commit = (method, ...args) => {
    this.mutations[method](...args)
  }
  // 触发异步
  dispatch(actionName, ...args) {
    this.actions[actionName](...args)
  }
}

let install = function (_Vue) {
  Vue = _Vue
  Vue.mixin({
    beforeCreate() {
      if (this.$options && this.$options.store) {
        this.$store = this.$options.store
      } else {
        // 子组件
        // 父组件和子组件的执行顺序
        // 父beforeCreate-> 父created -> 父beforeMounte -> 子beforeCreate ->子create ->子beforeMount ->子 mounted -> 父mounted
        this.$store = this.$parent && this.$parent.$store
      }
    },
  })
}

export default {
  Store,
  install
}
